package com.hqhy.like.admin.order.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.hqhy.like.admin.order.pojo.vo.OrderDetailsStandardVO;
import com.hqhy.like.admin.order.pojo.vo.OrderEcharts2VO;
import com.hqhy.like.admin.order.pojo.vo.OrderEchartsVO;
import com.hqhy.like.admin.order.pojo.vo.OrderListVO;
import com.hqhy.like.admin.order.service.IOrderService;
import com.hqhy.like.common.pojo.vo.PageData;
import com.hqhy.like.common.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/orders")
@Validated
@Api(tags = "订单管理")
public class OrderAdminController {
    @Autowired
    private IOrderService orderService;

    @GetMapping("")
    @ApiOperation("查询订单列表")
    @ApiOperationSupport(order = 410)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "页码",defaultValue = "1",paramType = "query",dataType = "int"),
            @ApiImplicitParam(name = "pageSize",value = "每页显示数据数",defaultValue = "1",paramType = "query",dataType = "int")
    })
    public JsonResult listOrders(@Range(min = 1,message = "请提交有效的页码值") Integer pageNum,Integer pageSize){
        log.debug("开始处理【查询订单列表】的请求，页码：{}", pageNum,pageSize);
        PageData<OrderListVO> pageData = orderService.ListOrder(pageNum,pageSize);
        return JsonResult.ok(pageData);
    }

    @GetMapping("/orderNo")
    @ApiOperation("根据订单编号查询订单")
    @ApiOperationSupport(order = 440)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo",value = "订单编号",required = true,paramType = "query",dataType = "String")
    })
    public JsonResult orderByOrderNo( String orderNo){
        log.debug("开始处理【根据订单编号查询订单】的请求，订单编号：{}", orderNo);
        List<OrderListVO> orderListVO = orderService.OrderByOrderNo(orderNo);
        return JsonResult.ok(orderListVO);
    }


    @GetMapping("/orderDetails")
    @ApiOperation("查询订单详情列表")
    @ApiOperationSupport(order = 420)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum",value = "页码",defaultValue = "1",paramType = "query",dataType = "int")
    })
    public JsonResult listOrderDetails(@Range(min = 1,message = "请提交有效的页码值") Integer pageNum,Integer pageSize){
        log.debug("开始处理【查询订单详情列表】的请求，页码：{}", pageNum,pageSize);
        PageData<OrderDetailsStandardVO> pageData = orderService.ListOrderDetails(pageNum,pageSize);
        return JsonResult.ok(pageData);
    }




    @GetMapping("/orderId")
    @ApiOperation("根据订单ID查询订单详情")
    @ApiOperationSupport(order = 430)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId",value = "订单Id",required = true,paramType = "query",dataType = "long")
    })
    public JsonResult OrderDetailsByOrderId(Long orderId){
        /*log.debug("开始处理【查询订单详情】的请求，订单Id：{}", orderId);
        List<OrderStandardVO> orderVO = orderService.OrderDetailsById(orderId);
        return JsonResult.ok(orderVO);*/
        log.debug("开始处理【查询订单详情】的请求，订单Id：{}", orderId);
        List<OrderDetailsStandardVO> orderVO = orderService.OrderDetailsById(orderId);
        return JsonResult.ok(orderVO);
    }

    @GetMapping("/delete")
    @ApiOperation("根据id删除订单")
    @ApiOperationSupport(order = 450)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "数据ID",required = true,paramType = "query",dataType = "long")
    })
    public JsonResult deleteById(Long id){
        log.debug("开始处理【删除订单详情】的请求，数据Id：{}",id);

        orderService.deleteById(id);
        return JsonResult.ok();
    }

    @GetMapping("/deletes")
    @ApiOperation("根据id删除订单详情")
    @ApiOperationSupport(order = 460)
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id",value = "数据ID",required = true,paramType = "query",dataType = "long")
    )
    public JsonResult deleteByOrderId(Long id){
        log.debug("开始处理【删除订单详情】的请求，订单Id：{}",id);
        orderService.deleteDetailsById(id);
        return JsonResult.ok();
    }

    @GetMapping("/charts")
    public JsonResult charts(){
        log.debug("开始处理【主页统计】的请求");
         List<OrderEchartsVO> list =  orderService.getOrderByDate();
         List<OrderEcharts2VO> list2 = orderService.getEcharts();
         //统计当日销售的所有菜系
        Set<String> dish=list.stream().map(OrderEchartsVO::getDishCuisine).collect(Collectors.toSet());
        List<Dict> barlist = new ArrayList<>();

        //统计各菜品销量
        for (String item:dish){
            long sum = list.stream().
                    filter(o -> o.getDishCuisine().equals(item))
                    .mapToLong(OrderEchartsVO::getDishNum)
                    .sum();
            Dict dict = Dict.create();
            Dict bar = dict.set("cuisine", item).set("value", sum);
            barlist.add(bar);
        }

        Set<String> dates = list2.stream().map(OrderEcharts2VO::getTime).collect(Collectors.toSet());
        ArrayList<String> dateList = CollUtil.newArrayList(dates);
        dateList.sort(Comparator.naturalOrder());
        List<Dict> linelist = new ArrayList<>();

        for (String date:dateList){
            BigDecimal sum = list2.stream().filter(o->o.getTime().equals(date)).map(OrderEcharts2VO::getTotalPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            Dict dict = Dict.create();
            Dict line = dict.set("date",date).set("value",sum);
            linelist.add(line);
        }

        Dict res =Dict.create().set("line",linelist).set("bar",barlist);
        return JsonResult.ok(res);
    }
}
